<template>
  <div class="video-player-modal" v-if="visible" @click.self="closePlayer">
    <div class="video-player-container">
      <div class="video-wrapper">
        <video v-if="video.play_url" ref="videoElement" :src="video.play_url"
          :poster="video.cover_url || defaultCoverImage" class="video-element" :muted="isMuted" loop playsinline
          webkit-playsinline @click="togglePlayPause" @loadedmetadata="onVideoLoaded" @error="handleVideoError"></video>

        <!-- 视频错误提示 -->
        <div v-if="videoError" class="video-error">
          <div class="error-icon">⚠️</div>
          <p>视频加载失败</p>
          <button @click="closePlayer" class="error-btn">关闭</button>
        </div>

        <!-- 加载中 -->
        <div v-if="loading && !videoError" class="video-loading">
          <div class="loading-spinner">⏳</div>
          <p>加载中...</p>
        </div>

        <!-- 播放按钮 -->
        <div v-if="paused && !loading && !videoError" class="play-button" @click.stop="togglePlayPause">
          ▶️
        </div>

        <!-- 关闭按钮 -->
        <div class="close-button" @click.stop="closePlayer">
          ✕
        </div>
      </div>

      <!-- 右侧操作栏 -->
      <div class="action-bar">
        <!-- 作者头像 -->
        <div class="avatar">
          <img :src="authorAvatar" :alt="authorName" />
        </div>

        <!-- 点赞 -->
        <div class="action-item" @click.stop="toggleLike">
          <div class="action-icon" :class="{ liked: video.is_favorite }">
            {{ video.is_favorite ? '❤️' : '🤍' }}
          </div>
          <span class="action-count">{{ formatCount(video.favorite_count) }}</span>
        </div>
      </div>

      <!-- 底部信息 -->
      <div class="video-info">
        <div class="author-info">
          <span class="author-name">@{{ authorName }}</span>
        </div>
        <div class="video-title">{{ video.title }}</div>
      </div>

      <!-- 静音控制 -->
      <div class="mute-control" @click.stop="toggleMute">
        {{ isMuted ? '🔇' : '🔊' }}
      </div>
    </div>
  </div>
</template>

<script>
import { mapActions } from 'vuex'

export default {
  name: 'VideoPlayer',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    video: {
      type: Object,
      required: true
    }
  },
  data() {
    return {
      loading: true,
      paused: true,
      isMuted: true,
      videoError: false,
      // 默认头像（使用本地图片）
      defaultAvatar: require('@/assets/avatar.png'),
      // 默认封面图（base64编码）
      defaultCoverImage: ''
    }
  },
  computed: {
    // 获取作者名称，兼容不同的字段名
    authorName() {
      if (!this.video.author) return '未知用户';
      return this.video.author.name || this.video.author.username || '未知用户';
    },
    // 获取作者头像，兼容不同的字段名
    authorAvatar() {
      if (!this.video.author) return this.defaultAvatar;
      return this.video.author.avatar || this.defaultAvatar;
    }
  },
  watch: {
    visible(newVal) {
      if (newVal) {
        this.$nextTick(() => {
          this.initVideo()
        })
      } else {
        this.pauseVideo()
      }
    }
  },
  methods: {
    ...mapActions(['toggleFavorite']),

    initVideo() {
      this.loading = true
      this.paused = true

      const videoElement = this.$refs.videoElement
      if (videoElement) {
        videoElement.currentTime = 0
        videoElement.muted = this.isMuted
      }
    },

    onVideoLoaded() {
      this.loading = false
      this.playVideo()
    },

    playVideo() {
      const videoElement = this.$refs.videoElement
      if (videoElement) {
        videoElement.play().catch(e => console.log('播放失败:', e))
        this.paused = false
      }
    },

    pauseVideo() {
      const videoElement = this.$refs.videoElement
      if (videoElement) {
        videoElement.pause()
        this.paused = true
      }
    },

    togglePlayPause() {
      const videoElement = this.$refs.videoElement
      if (videoElement) {
        if (videoElement.paused) {
          this.playVideo()
        } else {
          this.pauseVideo()
        }
      }
    },

    toggleMute() {
      this.isMuted = !this.isMuted
      const videoElement = this.$refs.videoElement
      if (videoElement) {
        videoElement.muted = this.isMuted
      }
    },

    async toggleLike() {
      if (!this.$store.getters.isLoggedIn) {
        this.$message.warning('请先登录')
        this.$router.push('/login')
        return
      }

      try {
        // 先记录原始状态
        const originalFavorite = this.video.is_favorite;
        const originalCount = this.video.favorite_count || 0;

        console.log('点赞前状态 - 视频ID:', this.video.id, '已点赞:', originalFavorite, '点赞数:', originalCount);

        // 乐观更新UI
        this.$set(this.video, 'is_favorite', !originalFavorite);
        const newCount = originalCount + (originalFavorite ? -1 : 1);
        this.$set(this.video, 'favorite_count', newCount);

        console.log('点赞后状态 - 视频ID:', this.video.id, '已点赞:', !originalFavorite, '点赞数:', newCount);

        // 然后发送API请求
        await this.toggleFavorite({
          videoId: this.video.id.toString(),
          actionType: originalFavorite ? 2 : 1 // 1: 点赞, 2: 取消点赞
        });

        console.log('API请求完成后 - 视频ID:', this.video.id, '已点赞:', this.video.is_favorite, '点赞数:', this.video.favorite_count);

        // 通知父组件更新累计点赞数
        this.$emit('like-toggled', {
          videoId: this.video.id,
          isLiked: !originalFavorite,
          countChange: originalFavorite ? -1 : 1
        });

      } catch (error) {
        console.error('点赞失败:', error);
        // 发生错误时恢复UI状态
        const isFavorite = this.video.is_favorite;
        this.$set(this.video, 'is_favorite', !isFavorite);
        this.$set(
          this.video,
          'favorite_count',
          (this.video.favorite_count || 0) + (isFavorite ? -1 : 1)
        );
        this.$message.error('操作失败');
      }
    },

    closePlayer() {
      this.$emit('close')
    },

    // 格式化数字
    formatCount(count) {
      if (!count) return '0'
      if (count < 1000) return count.toString()
      if (count < 10000) return (count / 1000).toFixed(1) + 'k'
      return (count / 10000).toFixed(1) + 'w'
    },

    handleVideoError() {
      this.videoError = true
      this.loading = false
      this.paused = true
    }
  },
  beforeDestroy() {
    this.pauseVideo()
  }
}
</script>

<style scoped>
.video-player-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #000;
  z-index: 1000;
  display: flex;
  align-items: center;
  justify-content: center;
  backdrop-filter: blur(5px);
}

.video-player-container {
  position: relative;
  width: 100%;
  height: 100%;
  margin: 0 auto;
  overflow: hidden;
  display: flex;
  align-items: center;
  justify-content: center;
}

.video-wrapper {
  width: 100%;
  height: 100%;
  position: relative;
  background: #000;
  display: flex;
  align-items: center;
  justify-content: center;
}

.video-element {
  max-width: 100%;
  max-height: 100%;
  width: auto;
  height: auto;
  object-fit: contain;
  cursor: pointer;
}

.video-loading {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  text-align: center;
  color: white;
}

.loading-spinner {
  font-size: 30px;
  animation: spin 1s linear infinite;
  margin-bottom: 10px;
}

.play-button {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 80px;
  height: 80px;
  background: rgba(255, 255, 255, 0.3);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 30px;
  cursor: pointer;
  backdrop-filter: blur(10px);
  color: white;
}

.close-button {
  position: absolute;
  top: 20px;
  right: 20px;
  width: 40px;
  height: 40px;
  background: rgba(0, 0, 0, 0.5);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 16px;
  cursor: pointer;
  z-index: 10;
  color: white;
  backdrop-filter: blur(10px);
}

.action-bar {
  position: absolute;
  right: 15px;
  bottom: 120px;
  display: flex;
  flex-direction: column;
  gap: 15px;
  align-items: center;
  z-index: 5;
}

.avatar {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  border: 2px solid white;
  overflow: hidden;
  position: relative;
  cursor: pointer;
}

.avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.action-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 5px;
  cursor: pointer;
  color: white;
}

.action-icon {
  width: 45px;
  height: 45px;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.1);
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
  transition: all 0.3s ease;
  backdrop-filter: blur(10px);
}

.action-icon.liked {
  background: rgba(255, 45, 85, 0.2);
  transform: scale(1.1);
}

.action-count {
  font-size: 12px;
  font-weight: 500;
}

.video-info {
  position: absolute;
  left: 15px;
  bottom: 120px;
  right: 80px;
  color: white;
  z-index: 5;
  background: linear-gradient(transparent, rgba(0, 0, 0, 0.7));
  padding: 20px 10px 10px 10px;
  border-radius: 8px;
}

.author-info {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 8px;
}

.author-name {
  font-weight: bold;
  font-size: 16px;
}

.video-title {
  font-size: 14px;
  line-height: 1.4;
  margin-bottom: 8px;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.mute-control {
  position: absolute;
  top: 70px;
  right: 20px;
  width: 40px;
  height: 40px;
  background: rgba(0, 0, 0, 0.5);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  font-size: 18px;
  z-index: 9;
  color: white;
  backdrop-filter: blur(10px);
}

@keyframes spin {
  from {
    transform: rotate(0deg);
  }

  to {
    transform: rotate(360deg);
  }
}

/* 移动端优化 */
@media (max-width: 480px) {
  .video-info {
    left: 10px;
    right: 70px;
    bottom: 80px;
    padding: 15px 8px 8px 8px;
  }

  .action-bar {
    right: 10px;
    bottom: 80px;
    gap: 12px;
  }

  .action-icon {
    width: 40px;
    height: 40px;
    font-size: 18px;
  }

  .avatar {
    width: 45px;
    height: 45px;
  }

  .close-button,
  .mute-control {
    width: 35px;
    height: 35px;
    font-size: 14px;
  }

  .close-button {
    top: 15px;
    right: 15px;
  }

  .mute-control {
    top: 60px;
    right: 15px;
  }

  /* 横屏手机的特殊处理 */
  @media (orientation: landscape) {
    .video-element {
      max-width: 95%;
      /* 在横屏模式下稍微减小最大宽度，留出边距 */
    }

    .action-bar {
      bottom: 50px;
      right: 5px;
    }

    .video-info {
      bottom: 50px;
      left: 5px;
    }
  }
}

.video-error {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  text-align: center;
  color: white;
  background: rgba(0, 0, 0, 0.7);
  padding: 20px 30px;
  border-radius: 12px;
  backdrop-filter: blur(10px);
}

.error-icon {
  font-size: 40px;
  margin-bottom: 15px;
}

.error-btn {
  margin-top: 20px;
  padding: 8px 20px;
  background: linear-gradient(135deg, #ff2d92, #ff6b35);
  border: none;
  border-radius: 20px;
  color: white;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s;
}

.error-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 5px 15px rgba(255, 45, 146, 0.4);
}
</style>